package com.framework.core.text;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;

public class SaesStringUtil {
	
	/**
	 * SEA版本号
	 */
	public static String seaVersion;
	
	public static String getSeaVersion() {
		return seaVersion;
	}

	public static void setSeaVersion(String seaVersion) {
		SaesStringUtil.seaVersion = seaVersion;
	}

	/**
	 * 获取数组维度值
	 * @param str
	 * @return
	 */
	public static String GetStringByArray(String[] str){
		String s="";
		for(String stritem:str){
			if(!StringUtils.isEmpty(stritem))
				s=stritem;
			else
				break;
		}
		
		return s;
	}
	
	/**
	 * 获取泛型的Collection Type
	 * @param jsonStr json字符串
	 * @param collectionClass 泛型的Collection
	 * @param elementClasses 元素类型
	 */
	public static <T> T readJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses) throws Exception {
	      ObjectMapper mapper = new ObjectMapper();
	      JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	      return mapper.readValue(jsonStr, javaType);
	}
	
	/**
	 * Json转实体
	 * @param jsonStr
	 * @param clazz
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static <T> T readJson(String jsonStr,Class<T> clazz) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(jsonStr,clazz);
	}
	
	/**
	 * Map转化为对象
	 * @param map 待转换的数据
	 * @param clazz 待转换的类
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IntrospectionException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static <T> T readMap(Map<String,Object> map,Class<T> clazz) throws InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException{
		T obj=clazz.newInstance();
	    BeanInfo bean=Introspector.getBeanInfo(clazz);
	    PropertyDescriptor[] props=bean.getPropertyDescriptors();
	    for(PropertyDescriptor prop:props){
	    	String proName=prop.getName();
	    	Object objValue=map.get(proName);
    		if(objValue==null)
    			continue;
    		
    		String prName=prop.getPropertyType().getName();
    		
	    	if(map.containsKey(proName)){
		    	if("java.math.BigDecimal".equals(prName)){
	    			try{
	    				BigDecimal v=new BigDecimal(objValue.toString());
	    				prop.getWriteMethod().invoke(obj, new Object[]{v});
	    			}catch(Exception ex){
	    				continue;
	    			}
		    	}else if("java.util.Date".equals(prName)){
	    			try{
	    				Date d=new Date(Long.parseLong(objValue.toString()));
	    				prop.getWriteMethod().invoke(obj, new Object[]{d});
	    			}catch(Exception ex){
	    				continue;
	    			}
		    	}else if("java.lang.Integer".equals(prName)){
		    		try{
	    				Integer d=new Integer(objValue.toString());
	    				prop.getWriteMethod().invoke(obj, new Object[]{d});
	    			}catch(Exception ex){
	    				continue;
	    			}
		    	}else if("java.lang.Double".equals(prName)){
		    		try{
	    				Double d=new Double(objValue.toString());
	    				prop.getWriteMethod().invoke(obj, new Object[]{d});
	    			}catch(Exception ex){
	    				continue;
	    			}
		    	}else
		    		prop.getWriteMethod().invoke(obj, new Object[]{objValue});
	    	}
	    }
	    
	    return obj;
	}
	
	
	/**
	 * 去字符串两边的空格， tab 换行
	 * @param str
	 * @return
	 */
	public static String Trim(String strValue){
		if(strValue==null)return null;
		String strResult="";
        for (int i=0,j=strValue.length();i<j;i++){
            char charTemp=strValue.charAt(i);
            if (charTemp!=' '&&charTemp!='\t'&&charTemp!='\n'&&charTemp!=' ') {
                strResult=strValue.substring(i);
                break;
            }
        }
        for (int i=strResult.length()-1;i>=0;i--){
            char charTemp = strResult.charAt(i);
            if (charTemp!=' '&&charTemp!='\t'&&charTemp!='\n'&&charTemp!=' ') {
                strResult=strResult.substring(0, i+1);
                break;
            }
        }
        return strResult;
	}
	
	
	/**
	 * xml转Map
	 * @param strxml
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> doXMLParse(String strxml) throws Exception {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

		if(null == strxml || "".equals(strxml))return null;
        
        Map<String, String> m = new HashMap<String, String>();
        
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
        	Element e = (Element) it.next();
        	String k = e.getName();
        	String v = "";
        	List children = e.getChildren();
        	if(children.isEmpty()) {
        		v = e.getTextNormalize();
        	} else {
        		v = getChildrenText(children);
        	}
            
        	m.put(k, v);
        }
        //关闭流
        in.close();
        return m;
	}
	
	/**
	 * 获取子节点的xml
	 * @param children
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
	
	/**
	 * 判断字符串是否是正整数
	 * @param str
	 * @return
	 */
	public static boolean isInteger(String str){
		try{
			Integer.valueOf(str);
			return true;
		}catch(Exception e){
			return false;
		}
	}
}
